<template>
	<div class="websocket-page">
		<!-- <h1>websokect实现实时聊天，可单聊、可群聊</h1> -->
		<form style="margin-top: 1rem; text-align: right">
			<el-input
				placeholder="REGIST"
				style="width: 30%; margin-right: 1rem"
				v-model="registId"></el-input>
			<el-button
				native-type="submit"
				@click.prevent="regist"
				>注册</el-button
			>
		</form>
		<form style="margin-top: 1rem; text-align: right" v-if="!user || JSON.stringify(user) === '{}'">
			<el-input
				placeholder="USERNAME"
				style="width: 30%; margin-right: 1rem"
				v-model="userId"></el-input>
			<el-button
				native-type="submit"
				@click.prevent="login"
				>登录</el-button>
		</form>
		<el-button @click="getRecommandList">获取推荐列表</el-button>
		<ul class="friend-recommand-list">
			<li v-if="recommandList && recommandList.length === 0">没有什么可以推荐的</li>
			<li
				v-else
				class="friend-recommand-item"
				v-for="recommand in recommandList">
				<span>{{ recommand.userId }}</span>
				<el-button @click="addFriend(recommand.userId)">添加</el-button>
			</li>
		</ul>
		<div class="websocket">
			<div class="websocket-left">
				<h3>通知</h3>
				<ul class="websocket-friend-list">
					<li
						class="friend-item"
						v-for="friendRequest in friendRequestList">
						<p>{{ friendRequest.msg }}123</p>
					</li>
				</ul>
				<h3>好友列表</h3>
				<ul class="websocket-friend-list">
					<li
						class="friend-item"
						v-for="friend in friendList"
						:class="{ 'friend-item-select': friend.roomId === currentRoomId }"
						@click="chooseChatRoom(friend)">
						<p>{{ friend.userId }}</p>
						<p
							v-if="msgDraftBox[friend.roomId] && msgDraftBox[friend.roomId].msg && friend.roomId !== currentRoomId"
							class="draft-msg">
							草稿：{{ msgDraftBox[friend.roomId].msg }}
						</p>
					</li>
				</ul>
			</div>
			<div
				class="websocket-right"
				v-if="!currentRoomId"></div>
			<div
				class="websocket-right"
				v-else>
				<div class="websocket-message">
					<ul>
						<li
							v-for="msg in msgList"
							:class="{ isSelf: userId === msg.userId }">
							<span>{{ msg.userId }}</span>
							<span>{{ msg.message }}</span>
						</li>
					</ul>
				</div>
				<div class="websocket-send-msg">
					<div class="send-msg-tool">
						<div></div>
						<div class="send-msg-tool-right">
							<el-button @click.prevent="sentMsg">发送</el-button>
						</div>
					</div>
					<div class="send-input-content">
						<textarea
							class="send-input"
							v-model="msgDraftBox[currentRoomId].msg"></textarea>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';
import { SocketIOService } from './socket';
import { loginAPI, registAPI, getRecommandListAPI, addFriendAPI, getFriendRequestListAPI } from '@/api';
import { ElNotification } from 'element-plus';
import layoutStore from '@/store/index';

const layoutSe = layoutStore();

const user = computed(() => layoutSe.getUser);
const socket = computed(() => layoutSe.getSocket)
const friendRequestList = computed(() => {
	console.log('好友请求列表发生变化了');
	return layoutSe.getFriendRequestList
})

// 模拟注册功能
const registId = ref<string>('');
const regist = async () => {
	const res = await registAPI({ userId: registId.value });
	if (res.data.data.status === 'failure') {
		ElNotification.error({
			message: res.data.data.errMessage,
			showClose: false,
		});
	} else {
		ElNotification.success({
			message: '注册成功',
			showClose: false,
		});
		registId.value = '';
	}
};

const userId = ref<string>(user.value.userId);
// 当前所处聊天室的ID
const currentRoomId = ref<string>('');
// 好友列表
const friendList = ref<any>([]);
// 当前聊天框的聊天记录
const msgList = ref<any>([]);
// 消息草稿箱
const msgDraftBox = ref<any>({});

// 登录
const login = async () => {
	if (!userId.value) return;
	const res = await loginAPI({ userId: userId.value });
	if (res.data.code === 200) {
		ElNotification.success({
			message: '登录成功',
			showClose: false,
		});
		layoutSe.setToken(res.data.data.results.token);
		layoutSe.setUser({ userId: userId.value });
		connect();
	}
};
// 建立连接
const connect = async () => {
	if (!socket.value || JSON.stringify(socket.value) === '{}' || !socket.value.isConnected) {
		// 初始化  Socket 实例并与服务器建立连接
		const _socket = new SocketIOService({
			userId: userId.value,
		});
		layoutSe.setSocket(_socket)
		await _socket.initSocket();
		await getFriendRequestList()
	}
};

// 获取推荐列表
const recommandList = ref<any>([]);
const getRecommandList = async () => {
	const res = await getRecommandListAPI({ userId: userId.value });

	if (res.data.code === 200) {
		recommandList.value = res.data.data.results;
	}
};
// 添加好友
const addFriend = async (friendId: string) => {
	const res = await addFriendAPI({ userId: userId.value, friendId });
	if (res.data.code === 200) {
		ElNotification.success({
			message: '添加成功',
			showClose: false,
		});
		registId.value = '';
	}
};
// 获取好友请求信息列表
const getFriendRequestList = async() => {
	const res = await getFriendRequestListAPI({ userId: userId.value });
	if (res.data.code === 200) {
		layoutSe.setFriendRequestList(res.data.data.results)
		ElNotification.success({
			message: '获取好友请求信息列表请求成功',
			showClose: false,
		});
	}
};

// 通知栏
const historyMsgList = ref<any>([]);

// 选择聊天对象
const currentFriend = ref<any>();
const chooseChatRoom = (friend: any) => {
	const { roomId } = friend;
	currentRoomId.value = roomId;
	currentFriend.value = friend;
	if (!msgDraftBox.value[currentRoomId.value]) {
		msgDraftBox.value[currentRoomId.value] = {};
		msgDraftBox.value[currentRoomId.value].msg = '';
	}
};

// 发送消息
const sentMsg = () => {
	const { roomId } = currentFriend.value;
	console.log('roomId', roomId);
	if (!roomId || !msgDraftBox.value[roomId].msg) return;
	// 判断是否有建立连接
	console.log('socket.value', socket.value);
	if (socket.value?.isConnected) {
		socket.value.sendMsg(
			/*传递到服务端的参数*/ {
				roomId,
				msgFrom: userId.value,
				msgTo: currentFriend.value.userId,
				msg: msgDraftBox.value[roomId].msg,
			},
		);
		msgDraftBox.value[roomId].msg = '';
	}
};

// 断开连接
const loginOut = () => {
	socket.value?.isConnected && socket.value?.disconnect();
};
</script>

<style lang="scss" scoped>
.websocket-page {
	width: 100%;
	.friend-recommand-list {
		width: 100%;
		height: max-content;
		list-style-type: none;
		padding: 0.25rem;
		box-sizing: border-box;
		border-radius: 10px;
		border: 1px solid #505050;
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
		flex-direction: row;
		flex-wrap: wrap;
		margin-top: 1rem;

		.friend-recommand-item {
			width: 6rem;
			line-height: 1.5;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-direction: row;
		}
	}

	.websocket {
		width: 100%;
		height: 70vh;
		border: 1px solid #505050;
		border-radius: 10px;
		margin-top: 1rem;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		flex-direction: row;
		overflow: hidden;

		.websocket-left {
			width: 10rem;
			height: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: flex-start;
			flex-direction: column;
			border-right: 1px solid #505050;
			text-decoration: none;
			list-style-type: none;
			padding: 0.25rem;
			box-sizing: border-box;
			border-top-left-radius: 10px;
			border-bottom-left-radius: 10px;
			overflow: auto;

			.websocket-friend-list {
				box-sizing: border-box;
				border: 1px solid #505050;
				border-radius: 10px;
				width: 100%;
				height: 100%;
				overflow: hidden;

				.friend-item {
					box-sizing: border-box;
					width: 100%;
					border-bottom: 1px solid #505050;
					padding: 0.5rem 1rem;
					cursor: pointer;
					overflow: hidden;

					&:hover {
						background-color: #000;
						color: #fff;
					}

					.draft-msg {
						color: red;
					}
				}

				.friend-item-select {
					background-color: #000;
					color: #fff;
				}
			}
		}

		.websocket-right {
			flex: 1;
			height: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			flex-direction: column;

			.websocket-message {
				flex: 1;
				width: 100%;
			}

			.websocket-send-msg {
				width: 100%;
				height: 8rem;
				border-top: 1px solid #505050;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.send-msg-tool {
					width: 100%;
					height: 2.5rem;
					display: flex;
					justify-content: space-between;
					align-items: center;
					flex-direction: row;
					border-bottom: 1px solid #505050;
					padding: 0 10px;
					box-sizing: border-box;
				}

				.send-input-content {
					width: 100%;
					flex: 1;

					.send-input {
						width: 100%;
						height: 100%;
						border: none;
						resize: none;
						padding: 10px;
						overflow: auto;
						box-sizing: border-box;

						&:focus {
							border: none;
							outline: none;
						}
					}
				}
			}
		}
	}
}
</style>
